<?php

namespace app\controller\admin\cnf;

use app\bll\Plugin as BllPlugin;
use core\controller\AdminBase;
use Exception;
use Noodlehaus\Config;
use support\View;

class Plugin extends AdminBase
{

    public function index()
    {
        $bllPlugin = new BllPlugin();
        $plugins = $bllPlugin->paginator(
            title: request()->get('title', '')
        );
        View::assign('plugins', $plugins);
        return $this->view();
    }

    public function install()
    {
        if (is_post()) {
            try {
                $bllPlugin = new BllPlugin();
                $bllPlugin->install();
            } catch (Exception $ex) {
                return $this->error($ex->getMessage());
            }
            return $this->success();
        } else {
            return $this->view(frame: false);
        }
    }

    public function handleUpgrade()
    {
        if (request()->ispost()) {
            try {
                $bllPlugin = new BllPlugin();
                $bllPlugin->handleUpgrade(request()->get('id'));
            } catch (Exception $ex) {
                return $this->error($ex->getMessage());
            }
            return $this->success();
        } else {
            return $this->view(frame: false);
        }
    }

    public function unInstall()
    {
        try {
            $bllPlugin = new BllPlugin();
            $bllPlugin->unInstall(request()->post('id'));
        } catch (Exception $ex) {
            return $this->error($ex->getMessage());
        }
        return $this->success();
    }

    public function onlineUpgrade()
    {
        try {
            $bllPlugin = new BllPlugin();
            $bllPlugin->onlineUpgrade(request()->get('id'));
        } catch (Exception $ex) {
            return $this->error($ex->getMessage());
        }
        return $this->success();
    }

    public function setConfig()
    {
        $id         = request()->get('id');
        $bllPlugin  = new BllPlugin();
        $Plugininfo = $bllPlugin->find($id);


        if (is_post()) {
            try {
                $config = Config::load(base_path() . '/plugin/' . $Plugininfo['ident'] . '/config.ini');
                $data = request()->post();
                foreach ($data as $key => $d) {
                    $config->set('value.' . $key, $d);
                }
                
                $config->toFile(base_path() . '/plugin/' . $Plugininfo['ident'] . '/config.ini');
            } catch (Exception $ex) {
                return $this->error($ex->getMessage());
            }
            return $this->success();
        } else {

            $config = Config::load(base_path() . '/plugin/' . $Plugininfo['ident'] . '/config.ini');
            View::assign('config', $config->all());

            return $this->view(
                frame: false
            );
        }
    }
}
